<template>
  <div>
    <vTablePage
      :pageConfig="pageConfig"
      :tableData="tableData"
      :total="total"
      @changeEdit="changeEditType"
      @changePageNo="changePageNo"
      @changeSearch="changeSearch"
      @changeSelect="changeSelect"
    >
      <template #tableHeader>
        <div style="margin-bottom: 5px;">
          <el-button type="primary" size="default" @click="addRole">添加职位</el-button>
          <el-button type="primary" size="default" :disabled="selectIdArr.length ? false : true"
            @click="exportExcels" plain>批量导出
          </el-button>
        </div>
      </template>
    </vTablePage>
    <!-- 添加职位与更新已有职位的结构:对话框 -->
    <el-dialog v-model="addDialog" :title="RoleParams.id ? '更新职位' : '添加职位'">
      <el-form :model="RoleParams" :rules="rules" ref="form">
          <el-form-item label="职位名称" prop="roleName">
              <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
          </el-form-item>
      </el-form>
      <template #footer>
          <el-button type="primary" size="default" @click="addDialog = false">取消</el-button>
          <el-button type="primary" size="default" @click="save">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog
      v-model="delDialogVisible"
      title="删除"
      width="500"
    >
      <span>确定删除这条数据吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="closeDelete">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配职位的菜单权限与按钮的权限 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配菜单与按钮的权限</h4>
      </template>
      <template #default>
        <!-- 树形控件 -->
        <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
            :default-checked-keys="selectArr" :props="defaultProps" />
      </template>
      <template #footer>
        <div style="flex: auto">
            <el-button @click="drawer = false">取消</el-button>
            <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import vTablePage from '../../components/tablePage/index.vue'
import { reqRemoveRole, reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermisstion } from '@/api/acl/role';
import type { RoleResponseData, Records, RoleData, MenuResponseData, MenuList } from '@/api/acl/role/type'
import { exportExcel } from '@/utils/exporExcel'

// 表格配置
const pageConfig = reactive({
  // 是否展示头部
  showHeader: true,
  // 是否展示索引or多选
  showIndex: true,
  showSelection: true,
  // 列表
  columns:[
    {
      label: 'ID',
      prop: 'id',
    },
    {
      label: '职位名称',
      prop: 'roleName',
      search: true,
    },
    {
      label: '创建时间',
      prop: 'createTime'
    },
    {
      label: '更新时间',
      prop: 'updateTime'
    },
    {
      label: '操作',
      prop: 'operation',
      isEdit: true,
      isFixed: true
    }
  ],
  // 操作列
  editBtns:[
    {
      text: '分配权限',
      type: 'assignment',
      icon: 'User'
    },
    {
      text: '编辑',
      type: 'edit',
      icon: 'Edit'
    },
    {
      text: '删除',
      type: 'delete',
      icon: 'Delete'
    }
  ]
})
const tableData = ref([])
const total = ref<number>(0)
const pageNo = ref<number>(1)
let keyword = ref<string>('')
let selectIdArr = ref([])
const delDialogVisible = ref<boolean>(false)
const addDialog = ref<boolean>(false)
let drawer = ref<boolean>(false)
//存储用户权限的数据
let menuArr = ref<MenuList>([]);
//获取tree组件实例
let tree = ref<any>();
//存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([]);
//树形控件的测试数据
const defaultProps = {
  children: 'children',
  label: 'name'
}

const id = ref<number>(0)
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
    roleName: ''
})
//获取form组件实例
let form = ref<any>();
//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
      callBack();
  } else {
      callBack(new Error('职位名称至少两位'))
  }
}
//职位校验规则
const rules = {
  roleName: [
      { required: true, trigger: 'blur', validator: validatorRoleName }
  ]
}

// 编辑类型
const changeEditType = (val: any) => {
  const { item, row } = val
  if (item.type === 'assignment') {
    changeRole(row)
  } else if (item.type === 'edit') {
    changeEdit(row)
  } else if (item.type === 'delete') {
    id.value = row.id
    delDialogVisible.value = true
  }
}
// 分页
const changePageNo = (row: any) => {
  pageNo.value = row
  getList()
}
// 获取选中数据
const changeSelect = (row: any) => {  
  selectIdArr.value = row
}
// 编辑职位
const changeEdit = (row: any) => {
  addDialog.value = true;
  Object.assign(RoleParams, row);
}

//确定按钮的回调
const save = async () => {
  await form.value.validate();
  //添加职位|更新职位的请求
  let result: any = await reqAddOrUpdateRole(RoleParams);
  if (result.code == 200) {
    //提示文字
    ElMessage({ type: 'success', message: RoleParams.id ? '更新成功' : '添加成功' });
    //对话框显示
    addDialog.value = false;
    getList()
  }
}

// 搜索
const changeSearch = (row: any) => {
  keyword.value = row.roleName ? row.roleName : ''
  getList()
}

// 分配权限
const changeRole = async(row: RoleData) => {
  drawer.value = true;
  //收集当前要分类权限的职位的数据
  Object.assign(RoleParams, row);
  //根据职位获取权限的数据
  let result: MenuResponseData = await reqAllMenuList((RoleParams.id as number));
  if (result.code == 200) {
    menuArr.value = result.data;
    selectArr.value = filterSelectArr(menuArr.value, []);
  }
}
// 筛选
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
        initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
        filterSelectArr(item.children, initArr);
    }
  })
  return initArr;
}
//抽屉确定按钮的回调
const handler = async () => {
  //职位的ID
  const roleId = (RoleParams.id as number);
  //选中节点的ID
  let arr = tree.value.getCheckedKeys();
  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys();
  let permissionId = arr.concat(arr1);
  //下发权限
  let result: any = await reqSetPermisstion(roleId, permissionId);
  if (result.code == 200) {
      //抽屉关闭
      drawer.value = false;
      //提示信息
      ElMessage({ type: 'success', message: '分配权限成功' });
      //页面刷新
      window.location.reload();
  }
}

// 添加职位
const addRole = () => {
  Object.assign(RoleParams, {
    roleName: '',
    id: 0
  })
  addDialog.value = true
}
// 删除
const closeDelete = async () => {
  let result: any = await reqRemoveRole(id.value);
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: 'success', message: '删除成功' });
    delDialogVisible.value = false
    getList()
  }
}
// 导出
const exportExcels = () => {
  exportExcel(pageConfig.columns, selectIdArr.value, '角色列表')
}
// 获取列表
const getList = async() => {
  let result: RoleResponseData = await reqAllRoleList(pageNo.value, keyword.value);
  if (result.code == 200) {
      total.value = result.data.total;
      tableData.value = result.data.records;
  }
}
onMounted(() => {
  getList()
})

</script>

<style scoped lang="scss">

</style>